package com.github.wxiaoqi.security.biz.api;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.wxiaoqi.security.common.msg.ResponseCode;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("upload")
public class fileUploadController {
	//private final String CATEGORY_TEST = "pics";
	//图片上传路径
	@Value("${communityImg.url}")
	private  String CATEGORY_HTTP;
	@Value("${communityImg.ip}")
	private  String CATEGORY_IP;
	/**
	 * 单文件上传
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/file", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		log.info("文件上传    请求文件：{}", file);
		Map<String, Object> respMap = new HashMap<String, Object>();
		log.info("文件上传    请求request：{}", request);
		if (!file.isEmpty()) {
			String oldFileName = file.getOriginalFilename();
			String suffix = oldFileName.substring(oldFileName.lastIndexOf('.'));
			String newFileName = UUID.randomUUID().toString() + suffix;
			
			File saveFile = new File(CATEGORY_HTTP + newFileName);
			if (!saveFile.getParentFile().exists()) {
				saveFile.getParentFile().mkdirs();
			}
//			byte[] bytes;
			try {
//				bytes = file.getBytes();
//				FileCopyUtils.copy(bytes, saveFile); // 保存文件
				file.transferTo(saveFile);
				respMap.put("filePath", CATEGORY_IP+"img/"+newFileName);
				respMap.put("code",ResponseCode.OK.getCode());
				respMap.put("msg", ResponseCode.OK.getMessage());
				respMap.put("success", true);
			} catch (IOException e) {
				e.printStackTrace();
				respMap.put("code",ResponseCode.UOLOAD_FILE_FAIL.getCode());
				respMap.put("msg", ResponseCode.UOLOAD_FILE_FAIL.getMessage());
				respMap.put("success", false);
			}
			
		} else {
			respMap.put("code",ResponseCode.UOLOAD_FILE_FAIL.getCode());
			respMap.put("msg", "上传文件为空");
			respMap.put("success", false);
		}
		return respMap;
	}

	/**
	 * 多文件上传
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/files", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadFiles(HttpServletRequest request) throws IOException {
		Map<String, Object> respMap = new HashMap<String, Object>();
		File savePath = new File(CATEGORY_HTTP);
		if (!savePath.exists()) {
			savePath.mkdirs();
		}
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		MultipartFile file = null;
		Map<String, Object> newFileNameMap = new HashMap<String, Object>();
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					String oldFileName = file.getOriginalFilename();
					String suffix = oldFileName.substring(oldFileName.lastIndexOf('.'));
					String newFileName = UUID.randomUUID().toString() + suffix;
					byte[] bytes = file.getBytes();
					File saveFile = new File(savePath, newFileName);
					FileCopyUtils.copy(bytes, saveFile); // 保存文件
					newFileNameMap.put("filePath"+i, saveFile.getAbsolutePath());
				} catch (Exception e) {
					respMap.put("code",ResponseCode.UOLOAD_FILE_FAIL.getCode());
					respMap.put("msg", ResponseCode.UOLOAD_FILE_FAIL.getMessage());
					respMap.put("success", false);
					return respMap;
				}
			} else {
				respMap.put("code",ResponseCode.UOLOAD_FILE_FAIL.getCode());
				respMap.put("msg", "上传文件为空");
				respMap.put("success", false);
				return respMap;
			}
		}
		respMap.put("filePathMap", newFileNameMap);
		respMap.put("code",ResponseCode.OK.getCode());
		respMap.put("msg", ResponseCode.OK.getMessage());
		respMap.put("success", true);
		return respMap;
	}
	
	/**
	 * 添加图片
	 */
	@ResponseBody
	@RequestMapping(value="/uploadImg", method=RequestMethod.POST)
	public Map<String, Object> uploadImg(HttpServletResponse response, HttpServletRequest request) {
		log.info("上传图片进来了。。。{}");
		MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;
	    MultipartFile multipartFile =  req.getFile("file");
	    Map<String, Object> respMap = new HashMap<String, Object>();	    
	    if (!multipartFile.isEmpty()) {
	 	    String oldFileName = multipartFile.getOriginalFilename();
	 	    String suffix = oldFileName.substring(oldFileName.lastIndexOf('.'));
	 	    String newFileName = UUID.randomUUID().toString() + suffix;
	 		try {
	 			File dir = new File(CATEGORY_HTTP);
	             if (!dir.exists()) {
	                 dir.mkdir();
	             }
	             File file1  =  new File(CATEGORY_HTTP,newFileName);
	             multipartFile.transferTo(file1);
	             respMap.put("filePath", CATEGORY_IP+"img/"+newFileName);
				 respMap.put("code",ResponseCode.OK.getCode());
				 respMap.put("msg", ResponseCode.OK.getMessage());
				 respMap.put("success", true);
	 	 		 log.info("添加图片返回。。。{}"+respMap);
	 		} catch (FileNotFoundException e) {
	 			e.printStackTrace();
				respMap.put("code",ResponseCode.UOLOAD_FILE_FAIL.getCode());
				respMap.put("msg", ResponseCode.UOLOAD_FILE_FAIL.getMessage());
				respMap.put("success", false);
	 		} catch (IOException e) {
	 			e.printStackTrace();
				respMap.put("code",ResponseCode.UOLOAD_FILE_FAIL.getCode());
				respMap.put("msg", ResponseCode.UOLOAD_FILE_FAIL.getMessage());
				respMap.put("success", false);
	 		}

		} else {
			respMap.put("code",ResponseCode.UOLOAD_FILE_FAIL.getCode());
			respMap.put("msg", "上传文件为空");
			respMap.put("success", false);
		}
		return respMap;

	}

}
